package com.tbit.uqbike.webmanager.controller;

import cn.hutool.core.collection.CollUtil;
import com.tbit.uqbike.constant.UserConstant;
import com.tbit.uqbike.object.business.SugarPost;
import com.tbit.uqbike.object.pojo.AlarmDayCount;
import com.tbit.uqbike.object.pojo.RideLog;
import com.tbit.uqbike.object.pojo.TerAlarm;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.NameObject;
import com.tbit.uqbike.object.view.OrderStatData;
import com.tbit.uqbike.object.view.sugar.*;
import com.tbit.uqbike.object.view.sugar.ride.SugarRideInfo;
import com.tbit.uqbike.service.base.SugarService;
import com.tbit.uqbike.service.rpcservice.MachineManagerService;
import com.tbit.uqbike.service.rpcservice.StatService;
import com.tbit.uqbike.webmanager.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author MyWin E-mail:335918956@qq.com
 * @version 1.0
 * @createTime 2019-12-16 18:50
 */
@Slf4j
@Validated
@RestController
@RequestMapping(value = "/sugar/data", produces = BaseController.MEDIA_JSON_UTF8)
public class SugarSupportController extends BaseController {

    @Autowired
    private SugarService sugarService;
    @Autowired
    private StatService statService;
    @Autowired
    private MachineManagerService machineManagerService;

    @RequestMapping("/statUser")
    public SugarResult statUser(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        List<NameObject> nos = statService.statNewUser(li, idList);
        List<SugarPieItem> data = SugarHelper.buildPies(nos, li.context);
        return SugarResult.ok(data);
    }

    /**
     * sugar总人数
     *
     * @param sugarPost
     * @param request
     * @return
     */
    @RequestMapping("/getTotalUserCnt")
    public SugarResult getTotalUserCnt(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        Integer cnt = sugarService.getTotalUserCnt(li, idList);
        return SugarResult.ok(cnt);
    }

    /**
     * sugar今日新增人数
     *
     * @param sugarPost
     * @param request
     * @return
     */
    @RequestMapping("/getTodayUserCnt")
    public SugarResult getTodayUserCnt(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        Integer cnt = sugarService.getTodayUserCnt(li, idList);
        return SugarResult.ok(cnt);
    }

    @RequestMapping("/getNearRide")
    /**实时订单消息*/
    public SugarResult getNearRide(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        List<RideLog> list = sugarService.getNearRide(li, idList);
        List<SugarTableItem> stiList = new LinkedList<>();
        for (RideLog rl : list) {
            SugarRideInfo sri = new SugarRideInfo(rl);
            sri.asterisk();
            stiList.add(sri);
        }
        return SugarResult.ok(new SugarTableData(SugarRideInfo.COLS, stiList, li.context));
    }


    /**
     * 总流水分布概览
     */
    @RequestMapping("/getFeeStat")
    public SugarResult getFeeStat(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        if (idList == null || idList.size() == 0) {
            idList.add(li.getId());
        }
        Map<String, Object> map = statService.statTotalData(li, idList, null, null);
        // 选择性的展示（只展示钱）
        map.remove(OrderStatData.PRO_TOTAL_DEPOSIT_ORDER);
        map.remove(OrderStatData.PRO_TOTAL_RECHARGE_ORDER);
        map.remove(OrderStatData.PRO_TOTAL_VIP_ORDER);
        map.remove(OrderStatData.PRO_TOTAL_FINE_ORDER);
        map.remove(OrderStatData.PRO_TOTAL_RIDE_ORDER);
        // 总金额隐藏
        map.remove(OrderStatData.PRO_TOTAL_ORDER);
        map.remove(OrderStatData.PRO_TOTAL_MONEY);
        /**移除骑行卡和vip卡*/
        map.remove(OrderStatData.PRO_TOTAL_DISCOUNT_ORDER);
        map.remove(OrderStatData.PRO_TOTAL_RIDECARD_ORDER);
        map.remove(OrderStatData.PRO_TOTAL_DISCOUNT_MONEY);
        map.remove(OrderStatData.PRO_TOTAL_RIDECARD_MONEY);
        /**移除罚款*/
        map.remove(OrderStatData.PRO_TOTAL_REFUND_MONEY);
        map.remove(OrderStatData.PRO_TOTAL_REFUND_ORDER);
        List<SugarPieItem> data = SugarHelper.buildPies(map, li.context);
        return SugarResult.ok(data);
    }


    /**
     * 昨日累计，同比增长等该区域展示数据
     */
    @RequestMapping("/getFeeCore")
    public SugarResult getFeeCore(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        CoreMoney cm = sugarService.getFeeCore(li, idList);
        List<SugarCoreItem> data = SugarHelper.buildCoreMoneyItems(cm);
        SugarHelper.buildCoreItems(data, li.context);
        return SugarResult.ok(data);
    }

    /**
     * sugar总流水
     *
     * @param sugarPost
     * @param request
     * @return
     */
    @RequestMapping("/getTotalMoney")
    public SugarResult getTotalMoney(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        Double data = sugarService.getSpeFee(li, idList, "totalMoney");
        return SugarResult.ok(data);
    }

    @RequestMapping("/getYesterDayMoney")
    public SugarResult getYesterDayMoney(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        Double data = sugarService.getSpeFee(li, idList, "yesterDayMoney");
        return SugarResult.ok(data);
    }

    @RequestMapping("/getYearYesterDayMoneyCompare")
    public SugarResult getYearYesterDayMoneyCompare(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        Double data = sugarService.getSpeFee(li, idList, "yearYesterDayMoneyCompare");
        return SugarResult.ok(data);
    }

    @RequestMapping("/getYesterDayMoneyCompare")
    public SugarResult getYesterDayMoneyCompare(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        Double data = sugarService.getSpeFee(li, idList, "yesterDayMoneyCompare");
        return SugarResult.ok(data);
    }

    @RequestMapping("/statAbnormal")
    /**统计异常部分（无信号，站外）*/
    public SugarResult statAbnormal(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        Map<String, Integer> map = machineManagerService.statAbnormal(li, idList);
        List<SugarPieItem> data = SugarHelper.buildPiesInt(map, li.context);
        return SugarResult.ok(data);
    }

    @RequestMapping("/statIdle")
    /**统计闲置（空闲部分）*/
    public SugarResult statIdle(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        Map<String, Integer> map = machineManagerService.statIdle(li, idList);
        List<SugarPieItem> data = SugarHelper.buildPiesInt(map, li.context);
        return SugarResult.ok(data);
    }

    @RequestMapping("/statBattery")
    /**统计电量信息（位置电量，中电量部分）*/
    public SugarResult statBattery(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        Map<String, Integer> map = machineManagerService.statBattery(li, idList);
        List<SugarPieItem> data = SugarHelper.buildPiesInt(map, li.context);
        return SugarResult.ok(data);
    }

    @RequestMapping("/statAllState")
    /**统计车辆状态（正常骑行故障异常部分）*/
    public SugarResult statAllState(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        Map<String, Integer> map = machineManagerService.statAllState(li, idList);
        List<SugarPieItem> data = SugarHelper.buildPiesInt(map, li.context);
        return SugarResult.ok(data);
    }

    @RequestMapping("/statTotalMoney")
    /**统计区域运营收入（运营大屏的部分是运营区域收入排行）*/
    public SugarResult statTotalMoney(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        Map<String, Double> map = sugarService.statTotalMoney(li, idList);
        HistogramData data = SugarHelper.buildHistogram("totalMoney", map, li.context);
        return SugarResult.ok(data);
    }

    @RequestMapping("/statAlarmCount")
    /**统计告警总数(不展示)*/
    public SugarResult statAlarmCount(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        Map<Integer, Integer> map = sugarService.statAlarmCount(li, idList);
        List<SugarCoreItem> data = SugarHelper.buildCoreAlarmItems(map);
        SugarHelper.buildCoreItems(data, li.context);
        return SugarResult.ok(data);
    }

    @RequestMapping("/statAlarmDetail")
    /**告警详情(不展示)*/
    public SugarResult statAlarmDetail(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        List<AlarmDayCount> alarmCntList = sugarService.statAlarmDetail(li, idList);
        Map<String, Map<Integer, Integer>> map = SugarHelper.initAlarmMap(alarmCntList);
        HistogramData data = HistogramData.buildDayModel(15);
        data.initData(map, li.context);
        return SugarResult.ok(data);
    }

    @RequestMapping("/queryAlarmInfo")
    /**(不展示)*/
    public SugarResult queryAlarmInfo(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        List<TerAlarm> alarmList = sugarService.queryAlarmInfo(li, idList);
        List<SugarTableItem> stiList = new LinkedList<>();
        for (TerAlarm ta : alarmList) {
            SugarAlarmInfo sri = new SugarAlarmInfo(ta);
            sri.asterisk();
            sri.alarmType = li.context.getMessage(sri.alarmType);
            stiList.add(sri);
        }
        return SugarResult.ok(new SugarTableData(SugarAlarmInfo.COLS, stiList, li.context));
    }

    @RequestMapping("/statTotalChangePower")
    /**今日换电总数（运维换电概念）*/
    public SugarResult statTotalChangePower(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        Map<String, Double> map = sugarService.statTotalChangePower(li, idList);
        HistogramData data = SugarHelper.buildHistogram("totalChangePower", map, li.context);
        return SugarResult.ok(data);
    }

    @RequestMapping("/replaceUrl")
    public SugarResult replaceUrl(@RequestBody SugarPost sugarPost, String baseUrl, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        List<Integer> ids = sugarService.filterAgent(li, idList);
        StringBuilder isSb = new StringBuilder();
        if (!UserConstant.USER_AGENT.equals(li.getType())) {
            ids.remove(li.getId());
        }
        for (Integer id : ids) {
            isSb.append(id).append(",");
        }
        if (isSb.length() > 0) {
            isSb.delete(isSb.length() - 1, isSb.length());
        }
        String url = String.format("%s?lang=%s&accountIds=%s&token=%s&zone=%d",
                sugarPost.querys.p == null ? baseUrl : sugarPost.querys.p, sugarPost.querys.lang, isSb.toString(), sugarPost.querys.token, sugarPost.querys.zone);
        return SugarResult.ok(url);
    }

    /**
     * 订单总数统计
     */
    @RequestMapping("/statRecharge")
    public SugarResult statRecharge(@RequestBody SugarPost sugarPost, HttpServletRequest request) {
        LoginInfo li = getLogin(request, sugarPost);
        List<Integer> idList = StringUtil.getIntegerList(sugarPost.querys.accountIds);
        if (CollUtil.isEmpty(idList)) {
            idList.add(li.getId());
        }
        List<NameObject> list = sugarService.statRecharge(li, idList, sugarPost.querys.brandId);
        return SugarResult.ok(list);
    }

}
